package com.ls.aicoderbackend.service.impl;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import com.ls.aicoderbackend.exception.BusinessException;
import com.ls.aicoderbackend.exception.ErrorCode;
import com.ls.aicoderbackend.exception.ThrowUtils;
import com.ls.aicoderbackend.manger.CosManager;
import com.ls.aicoderbackend.service.ScreenshotService;
import com.ls.aicoderbackend.utils.WebScreenshotUtils;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.io.File;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;

@Slf4j
@Service
public class ScreenshotServiceImpl implements ScreenshotService {

    @Resource
    private CosManager cosManager;

    /**
     * 生成并上传截图到COS
     * @param webUrl 网页url
     * @return 截图在COS的URL
     */
    @Override
    public String generateAndUploadScreenshot(String webUrl) {
        if (StrUtil.isBlank(webUrl)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "网页URL不能为空");
        }
        String localScreenshotPath = WebScreenshotUtils.saveWebPageScreenshot(webUrl);
        ThrowUtils.throwIf(StrUtil.isBlank(localScreenshotPath), ErrorCode.SYSTEM_ERROR, "截图失败");
        try {
            String pictureCosPath = uploadScreenshot(localScreenshotPath);
            ThrowUtils.throwIf(StrUtil.isBlank(pictureCosPath), ErrorCode.SYSTEM_ERROR, "截图上传失败");
            log.info("截图上传成功，{} -> {}", webUrl, pictureCosPath);
            return pictureCosPath;
        } finally {
            cleanupLocalFile(localScreenshotPath);
        }
    }


    /**
     * 上传截图到COS
     * @param localScreenshotPath 本地截图路径
     * @return 截图在COS的URL
     */
    private String uploadScreenshot(String localScreenshotPath) {
        if (StrUtil.isBlank(localScreenshotPath)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "截图路径不能为空");
        }
        File screenshotFile = FileUtil.file(localScreenshotPath);
        if (!screenshotFile.exists()) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "截图文件不存在");
        }
        String fileName = RandomUtil.randomString(8) + "_compressed.jpg";
        String cosKey = generateScreenshotKey(fileName);
        return cosManager.uploadFile(cosKey, screenshotFile);
    }

    /**
     * 生成截图前缀
     * @param fileName 文件名
     * @return 保存到COS的key
     */
    private String generateScreenshotKey(String fileName) {
        String formatTime = LocalDate.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
        return String.format("/screenshot/%s/%s", formatTime, fileName);
    }

    /**
     * 清楚本地截图
     * @param localScreenshotPath 本地截图路径
     */
    private void cleanupLocalFile(String localScreenshotPath) {
        File file = FileUtil.file(localScreenshotPath);
        if (file.exists()) {
            File parentDir = file.getParentFile();
            FileUtil.del(parentDir);
            log.info("本地截图文件已清理，{}", localScreenshotPath);
        }
    }

}
